// The Swift Programming Language
// https://docs.swift.org/swift-book

import UIKit
import RxAlamofire
import RxSwift
import Alamofire
import CryptoKit


@available(iOS 13.0.0, *)
public class Request {
    
    // TODO: 可能会要保持headers的时间戳参数值
    // 需要单独给个 headers 单例 / 将 Request 写成单例
    // 天气api的请求头
//    public static func weatherHeaders() ->HTTPHeaders?{
//        
//        var headers = HTTPHeaders([])
//        
//        let timestamp = Date().timestamp;
//        let header = ["alg": "EdDSA","kid": "C6WKQQKXH5"].toBase64URL()!
//        let payload = (["sub": "3JKQKB73W6","iat": timestamp-30,"exp": timestamp+30] as [String : Any]).toBase64URL()!
//        let keyString = "MC4CAQAwBQYDK2VwBCIEIEjRHG93P9cWmP1sLGCT+q0a/pcPDdVbXUZkYu33YBun"
//        
//        do{
//            
//            // 1. 解码 Base64 私钥字符
//            let privateKeyData = keyString.parsePKCS8Ed25519Key()!
//            // 2. 创建 Ed25519 私钥对象（实际使用 Curve25519.Signing）
//            let privateKey = try Curve25519.Signing.PrivateKey(rawRepresentation: privateKeyData)
//            // 3. 将消息转为 Data
//            let messageData = Data("\(header).\(payload)".utf8)
//            // 4. 生成 Ed25519 签名
//            let signature = try privateKey.signature(for: messageData).toBase64URL()
//            
//            // ["Authorization":"\(header).\(payload).\(signature)"]
//            headers.add(HTTPHeader(name: "Authorization", value: "Bearer \(header).\(payload).\(signature)"))
//            
//            
//        } catch  {
//            print("error: \(error)")
//            return nil
//        }
//        
//        return headers
//    }
    
    
    /**
     基础请求方法
     - parameter codeIndercept: 是否对返回code值拦截(正确通过，错误拦截)
     - parameter showError: 是否显示错误提示
     */
    public static func requestJSON(_ method: HTTPMethod,
                       _ url: URLConvertible,
                       parameters: Parameters? = nil,
                       encoding: ParameterEncoding = URLEncoding.default,
                       headers: HTTPHeaders? = nil,
                       interceptor: RequestInterceptor? = nil,
                       codeIntercept: Bool = true,
                       showError: Bool = true)
       -> Observable<(HTTPURLResponse, Any)> {
    
           return RxAlamofire.requestJSON(method,url, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor).map({ (response,json) -> (HTTPURLResponse, Any) in
               
               let dic = json as? [String:Any] ?? [:]
               
               var errorMsg = "服务器错误!请重试"
               switch response.statusCode {
                   case 200: //OK
                       break
                   case 201:
                       break
                   case 401:
                       errorMsg = "无授权!"
                       break
                   case 403:
                       errorMsg = "已被禁用!"
                       break
                   case 404:
                       errorMsg = "未找到"
                       break
                   default:
                       break
               }
               
               //网络失败提示 状态码!=200 errorCode != 0
               if codeIntercept && (dic["errorCode"] as? Int ?? 0 != 0 || response.statusCode != 200) {
//                   HUD.showHint(hint: dic["errMsg"] as? String ?? errorMsg)
                   return (response,[:])
               }
               
               if dic.keys.contains("body") {
                   return (response,dic["body"] as? [String:Any] ?? [:])
               }else{
                   return (response,dic)
               }
               
           }).do(onError: { error in
               if showError == true {
//                   await HUD.showHint(hint: "网络失败!")
               }
           })
           
   }
    
    
    
    
    
}
